﻿using MvcWechat.Common;
using MvcWechat.ServiceReference1;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace MvcWechat.Services
{
    /// <summary>
    /// 对应微信API的 "基础支持"
    /// </summary>
    public class BasicAPI
    {
        /// <summary>
        /// 检查签名是否正确:
        /// http://mp.weixin.qq.com/wiki/index.php?title=%E6%8E%A5%E5%85%A5%E6%8C%87%E5%8D%97
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="token">AccessToken</param>
        /// <returns>
        /// true: check signature success
        /// false: check failed, 非微信官方调用!
        /// </returns>
        public static bool CheckSignature(string signature, string timestamp, string nonce, string token, out string ent)
        {
            var arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray();
            var arrString = string.Join("", arr);
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
            StringBuilder enText = new StringBuilder();
            foreach (var b in sha1Arr)
            {
                enText.AppendFormat("{0:x2}", b); //x2表示十六进制格式（小写，大写用X2），域宽2位，不足的左边填0。
            }
            ent = enText.ToString();
            return signature == enText.ToString();
        }

        /// <summary>
        /// 获取AccessToken
        /// http://mp.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96access_token
        /// </summary>
        /// <param name="grant_type"></param>
        /// <param name="appid"></param>
        /// <param name="secrect"></param>
        /// <returns>access_toke</returns>
        public static dynamic GetAccessToken(string appid, string secrect)
        {
            dynamic token=null;
            try
            {
                //。net framework 4.5
                var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", appid, secrect);
                var client = new HttpClient();
                var result = client.GetAsync(url).Result;
                if (!result.IsSuccessStatusCode) return string.Empty;
                token = DynamicJson.Parse(result.Content.ReadAsStringAsync().Result);
                if (token.access_token!="")
                {

                }
                return token;
                //string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", appid, secrect);
                //string result = Util.RequestGetStr(url);
                //if (result == "") return string.Empty;
                //var token = DynamicJson.Parse(result);
                //return token;
            }
            catch (Exception ex)
            {//抛出自定义异常
                throw new MyException(string.Format("{0},{1}", ex.Message, token.errmsg));
            }
          
        }

        /// <summary>
        /// 上传多媒体文件
        /// http://mp.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E4%B8%8B%E8%BD%BD%E5%A4%9A%E5%AA%92%E4%BD%93%E6%96%87%E4%BB%B6
        /// 1.上传的媒体文件限制：
        ///图片（image) : 1MB，支持JPG格式
        ///语音（voice）：1MB，播放长度不超过60s，支持MP4格式
        ///视频（video）：10MB，支持MP4格式
        ///缩略图（thumb)：64KB，支持JPG格式
        ///2.媒体文件在后台保存时间为3天，即3天后media_id失效
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="type">媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）</param>
        /// <param name="file">本地完整路径</param>
        /// <returns>media_id</returns>
        public static string UploadMedia(string access_token, string type, string file)
        {
            var url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", access_token, type);
            var fileDictionary = new Dictionary<string, string>();
            fileDictionary["media"] = file;
            var returnText = Util.HttpRequestPost(url, fileDictionary);
            if (returnText.Contains("errcode"))
            {
                return string.Empty;
            }
            var media = DynamicJson.Parse(returnText);
            return media.media_id;
        }

        /// <summary>
        /// 下载多媒体
        /// 视频文件不支持下载，调用该接口需http协议。
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="media_id"></param>
        /// <param name="media_id"></param>
        /// <returns></returns>
        public static void DownloadMedia(string access_token, string media_id, Stream sm)
        {
            var url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", access_token, media_id);
            Util.Download(url, sm);
        }

        /// <summary>
        /// 得到自定义菜单 
        /// </summary>
        /// <param name="access_token">access_token</param>
        /// <returns></returns>
        public static dynamic GetConditionalMenu(string access_token)
        {

            //。net framework 4.5
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", access_token);
            var client = new HttpClient();
            var result = client.GetAsync(url).Result;
            if (!result.IsSuccessStatusCode) return string.Empty;
            var menu = result.Content.ReadAsStringAsync().Result;
            return menu;
            //string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", appid, secrect);
            //string result = Util.RequestGetStr(url);
            //if (result == "") return string.Empty;
            //var token = DynamicJson.Parse(result);
            //return token;
        }

        /// <summary>
        /// 得到用户信息 
        /// </summary>
        /// <param name="access_token">access_token</param>
        /// <returns></returns>
        public static dynamic GetUserInfo(string access_token, string openid)
        {

            //。net framework 4.5
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN ", access_token,openid);
            var client = new HttpClient();
            var result = client.GetAsync(url).Result;
            if (!result.IsSuccessStatusCode) return string.Empty;
            var userInfo = result.Content.ReadAsStringAsync().Result;
            return userInfo;
            //string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", appid, secrect);
            //string result = Util.RequestGetStr(url);
            //if (result == "") return string.Empty;
            //var token = DynamicJson.Parse(result);
            //return token;
        }
        //添加首次关注用户到数据库中 默认公众号用户
        public static bool AddUserInfo(string tagKey, string userJson,int type=0)
        {
            return new RetailClient().AddWXCustomer(tagKey, userJson,type);

        }

        /// <summary>
        /// 获取AccessToken
        /// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        /// </summary>
        /// <param name="grant_type"></param>
        /// <param name="appid"></param>
        /// <param name="secrect"></param>
        /// <returns>access_toke</returns>
        public static dynamic GetAccessTokenByWechatLogin(string appid, string secrect, string code)
        {
            dynamic token = null;
            try
            {
                //。net framework 4.5
                var url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type={3}", appid, secrect, code, "authorization_code");
                var client = new HttpClient();
                var result = client.GetAsync(url).Result;
                if (!result.IsSuccessStatusCode) return string.Empty;
                var returnStr=result.Content.ReadAsStringAsync().Result;
                if (returnStr.Contains("access_token"))
                {
                    token = DynamicJson.Parse(returnStr);
                }
                else {
                    token = new {access_token = "errcode" }; 
                }
                return token;

                //string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", appid, secrect);
                //string result = Util.RequestGetStr(url);
                //if (result == "") return string.Empty;
                //var token = DynamicJson.Parse(result);
                //return token;
            }
            catch (Exception ex)
            {//抛出自定义异常
                throw new MyException(string.Format("{0},{1}", ex.Message, token.errmsg));
            }

        }

        /// <summary>
        /// 得到用户信息 微信扫码登录  https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        /// </summary>
        /// <param name="access_token">access_token</param>
        /// <returns></returns>
        public static dynamic GetUserInfoByWechatLogin(string access_token, string openid)
        {

            //。net framework 4.5
            var url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}", access_token, openid);
            var client = new HttpClient();
            var result = client.GetAsync(url).Result;
            if (!result.IsSuccessStatusCode) return string.Empty;
            var userInfo = result.Content.ReadAsStringAsync().Result;
            return userInfo;
            //string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", appid, secrect);
            //string result = Util.RequestGetStr(url);
            //if (result == "") return string.Empty;
            //var token = DynamicJson.Parse(result);
            //return token;
        }
    }
}
